﻿module Sustainalytics.MostActiveReports {

    import Common = Sustainalytics.Common;

    export class MostActiveReportController {

        public reports: MostActiveReportDto[] = [];
        public skip: number;
        public take: number;

        constructor(
            private $rootScope: ng.IScope,
            private $scope: ng.IScope,
            private $q: ng.IQService,
            private $timeout: ng.ITimeoutService,
            private $location: ng.ILocationService,
            private MostActiveReportService: IMostActiveReportService) {

            var ctx = this;

            var initPromise = ctx.init();
        }

        private init(): ng.IPromise<any> {
            var ctx = this;

            ctx.skip = 0;
            ctx.take = 20;

            var reportsPromise = ctx.addReports();

            ctx.$scope.$watch('mar.skip', function (newSkip, oldSkip) {
                if (newSkip > oldSkip) {
                    ctx.addReports();
                }
            });

            return reportsPromise;
        }

        private addReports(): ng.IPromise<any> {
            var ctx = this;

            // load reports
            var reportsPromise = ctx.MostActiveReportService.getList(ctx.skip, ctx.take);

            ctx.$rootScope['loading'] = true;

            reportsPromise.then(function (reports) {
                    ctx.$timeout(function () {
                        ctx.$scope.$apply(function () {
                            ctx.reports.push.apply(ctx.reports, reports);
                        })
                    });
                });

            reportsPromise['finally'](function () {
                ctx.$rootScope['loading'] = false;
            });

            return reportsPromise;
        }

        public getReportMainTicker(report: MostActiveReportDto) {
            var ctx = this;

            if (report.ticker && report.exchange) {
                return report.ticker + ':' + report.exchange;
            }
            else {
                return null;
            }
        }

        public goToCompanyPage(report: MostActiveReportDto) {
            var ctx = this;

            if (report.inUniverse)
            {
                ctx.$location.url('/research/overview/' + report.companyNameUrlFriendly);
            }
        }
    }


    export var mostActiveReportControllerName = 'MostActiveReportController';

    angular.module(mostActiveReportsModuleName).controller(mostActiveReportControllerName,
        ['$rootScope', '$scope', '$q', '$timeout', '$location', 'MostActiveReportService', MostActiveReportController]);
}